package com.dji.sample.component.listener.handle;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dji.sample.common.constant.CommonConstant;
import com.dji.sample.component.listener.RedisMsgHandle;
import com.dji.sample.component.listener.recevice.RedisLiveReceive;
import com.dji.sample.component.redis.RedisConst;
import com.dji.sample.component.redis.RedisOpsUtils;
import com.dji.sample.component.websocket.config.ConcurrentWebSocketSession;
import com.dji.sample.component.websocket.model.BizCodeEnum;
import com.dji.sample.component.websocket.model.CustomWebSocketMessage;
import com.dji.sample.component.websocket.service.ISendMessageService;
import com.dji.sample.component.websocket.service.IWebSocketManageService;
import com.dji.sample.manage.model.dto.DeviceDTO;
import com.dji.sample.manage.model.dto.TopologyDeviceDTO;
import com.dji.sample.manage.model.enums.UserTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import java.util.Collection;
import java.util.Objects;

/**
 * @author yjt
 * @date 2023-02-09
 * @description:
 */
public class EndLiveHandle implements RedisMsgHandle {

    @Override
    public void dealMsg(String msg, String topic, ISendMessageService sendMessageService, IWebSocketManageService webSocketManageService, RedisOpsUtils redisOps) {
        if(!topic.equals(CommonConstant.END_LIVE)){
            return;
        }
        Collection<ConcurrentWebSocketSession> webSocketSessions = webSocketManageService.getValueWithWorkspaceAndUserType(CommonConstant.DEFAULT_WORK_SPACE_ID, UserTypeEnum.WEB.getVal());
        if (webSocketSessions.isEmpty()) {
            return;
        }
        RedisLiveReceive redisLiveReceive = JSONObject.parseObject(JSON.parse(msg).toString(), RedisLiveReceive.class);
        redisLiveReceive.setDeviceSn(redisLiveReceive.getRoomId());
        String keys = RedisConst.DEVICE_ONLINE_PREFIX + redisLiveReceive.getDeviceSn();
        Object o = redisOps.get(keys);
        if (!Objects.isNull(o)) {
            DeviceDTO device = (DeviceDTO) o;
            redisLiveReceive.setDeviceNo(device.getDeviceNo());
        }
        CustomWebSocketMessage message =
                CustomWebSocketMessage.builder()
                        .timestamp(System.currentTimeMillis())
                        .bizCode(BizCodeEnum.DEVICE_END_LIVE.getCode())
                        .data(redisLiveReceive)
                        .build();
        sendMessageService.sendBatch(UserTypeEnum.WEB.getVal(), webSocketSessions, message);
    }
}
